package com.blacksheep.mtm.service.Impl;

import com.blacksheep.mtm.common.exception.XmallException;
import com.blacksheep.mtm.common.jedis.JedisClient;
import com.blacksheep.mtm.dao.TbBoxRecycleMapper;
import com.blacksheep.mtm.dao.TbUserMapper;
import com.blacksheep.mtm.pojo.common.DataTablesResult;
import com.blacksheep.mtm.pojo.manager.TbBoxRecycle;
import com.blacksheep.mtm.service.BoxRecycleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class BoxRecycleServiceImpl implements BoxRecycleService {

    @Autowired
    private TbBoxRecycleMapper recycleMapper;
    @Autowired
    private TbUserMapper userMapper;

    @Autowired
    private JedisClient jedisClient;
    @Override
    public DataTablesResult getList(int draw, int start, int length,  int bindId, String orderCol, String orderDir) {
        DataTablesResult result=new DataTablesResult();
        PageHelper.startPage(start/length+1,length);
        List<TbBoxRecycle> list = recycleMapper.selectListByBindId(bindId,orderCol,orderDir);

        PageInfo<TbBoxRecycle> pageInfo=new PageInfo<>(list);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setDraw(draw);
        result.setData(list);

        return result;
    }

    @Override
    public int add(int bindId, String boxCode) {
        String username = SecurityUtils.getSubject().getPrincipal().toString();
        Long userId = userMapper.getUserIdByUsername(username);
        TbBoxRecycle recycle = new TbBoxRecycle();
        recycle.setBindId(bindId);
        recycle.setBoxCode(boxCode);
        recycle.setOperator(userId);
        recycle.setUid(UUID.randomUUID().toString());
        int result = recycleMapper.insertSelective(recycle);
        if (result <=0){
            throw  new XmallException("回收失败");
        }
        //回收之后,清楚redis里的记录
        jedisClient.del("BIND_ORDER_BOX_"+boxCode);
        return result;
    }

    @Override
    public int delete(Integer id) {
        int result = recycleMapper.deleteByPrimaryKey(id);
        return result;
    }
}
